package com.example.app0601;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity implements OnClickListener {
    private WebView webView;
    private EditText searchEditText;
    private Button btnBJ;
    private Button btnSH;
    private Button btnTJ;
    private static final int COLOR_CHANGE_DELAY = 3000; // 颜色变化延迟时间（毫秒）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("天气查询");

        btnBJ = findViewById(R.id.btnBJ);
        btnBJ.setOnClickListener(this);

        btnSH = findViewById(R.id.btnSH);
        btnSH.setOnClickListener(this);

        btnTJ = findViewById(R.id.btnTJ);
        btnTJ.setOnClickListener(this);

        Button searchButton = findViewById(R.id.btnSearch);
        searchButton.setOnClickListener(this);

        webView = findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://m.tianqi.com/beijing/");

        searchEditText = findViewById(R.id.etSearch);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnBJ:
                btnBJ.setBackgroundColor(getResources().getColor(R.color.clickedButtonColor));
                Handler handlerBJ = new Handler();
                handlerBJ.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        btnBJ.setBackgroundColor(Color.TRANSPARENT);
                    }
                }, COLOR_CHANGE_DELAY);
                openUrl("101010100");
                break;
            case R.id.btnSH:
                btnSH.setBackgroundColor(getResources().getColor(R.color.clickedButtonColor));
                Handler handlerSH = new Handler();
                handlerSH.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        btnSH.setBackgroundColor(Color.TRANSPARENT);
                    }
                }, COLOR_CHANGE_DELAY);
                openUrl("101020100");
                break;
            case R.id.btnTJ:
                btnTJ.setBackgroundColor(getResources().getColor(R.color.clickedButtonColor));
                Handler handlerTJ = new Handler();
                handlerTJ.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        btnTJ.setBackgroundColor(Color.TRANSPARENT);
                    }
                }, COLOR_CHANGE_DELAY);
                openUrl("101030100");
                break;
            case R.id.btnSearch:
                String input = searchEditText.getText().toString().trim();
                if (!input.isEmpty()) {
                    searchCity(input);
                }
                break;
        }
    }

    // 其他代码保持不变



    private void openUrl(String id) {
        String apiKey = "9c3b5002d468426b8d310589ed22223b";
        String apiUrl = "https://devapi.qweather.com/v7/weather/3d?location=" + id + "&key=" + apiKey;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(apiUrl)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败的情况
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        final String weatherData = responseBody.string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                webView.loadData(weatherData, "text/html", "UTF-8");
                            }
                        });
                    }
                } else {
                    // 处理请求失败的情况
                }
            }
        });
    }

    private void searchCity(String input) {
        String apiKey = "9c3b5002d468426b8d310589ed22223b";
        String apiUrl = "https://geoapi.qweather.com/v2/city/lookup?location=" + input + "&key=" + apiKey;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(apiUrl)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败的情况
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        final String cityData = responseBody.string();
                        // 解析城市数据并获取城市ID
                        String cityId = parseCityId(cityData);
                        if (cityId != null) {
                            // 根据城市ID查询天气
                            openUrl(cityId);
                        } else {
                            // 处理城市数据解析失败的情况
                        }
                    }
                } else {
                    // 处理请求失败的情况
                }
            }
        });
    }

    private String parseCityId(String cityData) {
        try {
            JSONObject jsonObject = new JSONObject(cityData);
            JSONArray locationArray = jsonObject.getJSONArray("location");
            if (locationArray.length() > 0) {
                JSONObject locationObject = locationArray.getJSONObject(0);
                return locationObject.getString("id");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
